let path = require('path')
let fileUtil = require('../utils/file_util')

var WebSocket = require("ws");
//创建服务端对象对象,端口9998
var wss = new WebSocket.Server({
    port: 9998
})

module.exports.listen = () => {
    wss.on('connection', client => {
        console.log('客户端调用成功...');
        client.on('message', async (msg) => {
            console.log('客户端发送数据给服务端: ' + msg)
            let payload = JSON.parse(msg)
            let action = payload.action

            if (action === 'getData') {
                // payload.chartName -> trend,seller,map,rank,hot,stock
                let filePath = '../data/' + payload.chartName + '.json'
                filePath = path.join(__dirname, filePath)
                let ret = await fileUtil.getFileJsonData(filePath)
                // 在payload中增加data字段,data对应的value就是json中的内容
                payload.data = ret
                client.send(JSON.stringify(payload))
            } else {
                // 将数据转发给所有的处于连接状态的客户端
                wss.clients.forEach(c => {
                    c.send(msg)
                })
            }
            // client.send('后端来的')
            // client.send(msg)
        })
    })
}

